<template>
	<view class="container">
		<!-- 收货信息 -->
		<!-- <view class="delivery-info" @click="selectAddress">
			<view class="address-icon">📍</view>
			<view class="address-content" v-if="hasAddress">
				<text class="address-text">{{ deliveryInfo.address }}</text>
				<text class="contact-info">{{ deliveryInfo.name }} {{ deliveryInfo.phone }}</text>
			</view>
			<view class="address-content" v-else>
				<text class="no-address-text">请添加收货地址</text>
			</view>
			<view class="custom-arrow"></view>
		</view> -->
		
		<!-- 收货日期 -->
		<!-- <view class="delivery-date" @click="selectDate">
			<text class="date-label">收货日期</text>
			<view class="date-content">
				<text class="date-text">{{ deliveryDate }}</text>
				<view class="custom-arrow">
					<view class="arrow-line"></view>
					<view class="arrow-head"></view>
				</view>
			</view>
		</view> -->
		
		<!-- 支付方式 -->
		<!-- <view class="payment-methods">
			<text class="payment-title">支付方式</text>
			<view 
				class="payment-item" 
				v-for="(method, index) in paymentMethods" 
				:key="index"
				@click="selectPaymentMethod(index)"
			>
				<view class="payment-info">
					<text class="payment-icon">{{ method.icon }}</text>
					<text class="payment-name">{{ method.name }}</text>
				</view>
				<view class="payment-radio" :class="{ active: selectedPaymentIndex === index }">
					<view class="radio-dot" v-if="selectedPaymentIndex === index"></view>
				</view>
			</view>
		</view> -->
		
		<!-- 转账记录上传 -->
		<!-- <view class="transfer-record-upload" v-if="paymentMethods[selectedPaymentIndex].value == '0'">
			<view class="transfer-record-upload-title">转账记录上传<text style="color: #ff4069;">*</text></view>
			<js-uploadfile v-model="image.dataMap" :biz-key="image.id" biz-type="order_transfer_image"></js-uploadfile>
		</view> -->
		<!-- 购买商品汇总 -->
		<!-- <view class="purchase-summary">
			<text class="summary-label">购买商品</text>
			<text class="summary-text">共{{ orderItems.length }}件,合计¥{{ totalPrice }}</text>
		</view> -->
		
		<!-- 店铺选择 -->
		<view class="shop-section">
			<view class="shop-header">
				<text class="shop-label">店铺名称</text>
			</view>
			<shop-selector v-model="shopModel" :shop-list="officeSelectList" :field-config="{
				valueField: 'dictValue',
				labelField: 'dictLabel',
				displayField: 'dictLabel',
				placeholder: '搜索/选择店铺名称',
				codeField: 'officeCode',
				nameField: 'officeName'
			}"></shop-selector>
		</view>
		
		<!-- 备注 -->
		<view class="remarks-section">
			<view class="remarks-header">
				<text class="remarks-label">备注</text>
				<text class="remarks-limit">限30字</text>
			</view>
			<textarea 
				class="remarks-input" 
				v-model="remarks" 
				placeholder="请填写备注信息"
				maxlength="30"
			></textarea>
		</view>
		
		<!-- 商品列表 -->
		<view class="order-items">
			<text class="order-items-title">商品详情</text>
			<view 
				class="order-item" 
				v-for="(item, index) in orderItems" 
				:key="index"
			>
				<image class="item-image" v-if="item.image" :src="item.image" mode="aspectFill"></image>
				<image class="item-image" style="border:1px solid #f0f0f0;" v-else src="../common/images/noImage.png" mode="aspectFill"></image>
				<view class="item-info">
					<text class="item-name">{{ item.name }}</text>
					<text class="item-costPrice" v-if="item.costPrice">¥{{ item.costPrice }}</text>
					<view class="item-details">
						<text class="item-price">¥{{ item.price }}</text>
						<text class="item-quantity">x{{ item.quantity }}</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 底部结算栏 -->
		<view class="order-footer">
			<view class="total-info">
				<view class="price-item">
					<text class="total-label">进货价:</text>
					<text class="total-price">¥{{ totalPrice }}</text>
				</view>
				<view class="price-item">
					<text class="total-label">零售价:</text>
					<text class="total-price">¥{{ totalCostPrice }}</text>
				</view>
			</view>
			<view class="submit-btn" @click="submitOrder">
				<text class="submit-text">提交订单</text>
			</view>
		</view>
	</view>
</template>

<script>
import ShopSelector from '@/components/shop-selector/shop-selector.vue'

export default {
	components: {
		ShopSelector
	},
	data() {
		return {
			orderItems: [],
			fromCart: false,
			remarks: '',
			selectedPaymentIndex: 0,
			deliveryInfo: {
				id: '',
				name: '',
				phone: '',
				address: ''
			},
			hasAddress: false, // 是否有地址
			// 收货日期
			deliveryDate: '',
			paymentMethods: [
				{
					icon: '💰',
					name: '线下转账',
					value: '0'
				},
				{
					icon: '💳',
					name: '暂不付款,计入欠款',//🏦 💵 💰 💳
					value: '1'
				},
			],
			image: {
				dataMap:{
					order_transfer_image: '',
					order_transfer_image__del: ''
				},
				id: ''
			},
			// 店铺选择
			shopModel: {
				officeCode: '',
				officeName: ''
			},
			officeSelectList: [] // 店铺列表
		}
	},
	onLoad(options) {
		if (options.cart) {
			console.log(options.cart)
			this.orderItems = JSON.parse(options.cart)
		}
		if (options.fromCart) {
			this.fromCart = options.fromCart
		}
		
		// 生成临时ID用于文件上传
		this.image.id = 'temp_' + Date.now()
		
		// 加载默认地址
		this.loadDefaultAddress()
		
		// 加载店铺列表
		this.loadShopList()
	},
	computed: {
		totalPrice() {
			let total = 0
			for (let item of this.orderItems) {
				total += item.price * item.quantity
			}
			return total
		},
		totalCostPrice() {
			let total = 0
			for (let item of this.orderItems) {
				total += item.costPrice * item.quantity
			}
			return total
		}
	},
	methods: {
		// 加载店铺列表
		loadShopList() {
			this.$u.api.mainType.treeData({dictType:'office_code'}).then(res => {
				this.officeSelectList = res || []
			}).catch(err => {
				console.error('获取店铺列表失败:', err)
				this.officeSelectList = []
			})
		},
		
		// 加载默认地址
		loadDefaultAddress() {
			this.$u.api.address.list().then(res => {
				if (res && res.data && res.data.length > 0) {
					// 查找默认地址 (isDefault 为 1 表示默认地址)
					let defaultAddress = res.data.find(item => item.isDefault == 1)
					
					// 如果没有默认地址，取第一个
					if (!defaultAddress) {
						defaultAddress = res.data[0]
					}
					
					// 设置地址信息（包括ID）
					this.deliveryInfo.id = defaultAddress.id || ''
					this.deliveryInfo.address = defaultAddress.address || ''
					this.deliveryInfo.name = defaultAddress.receiverName || ''
					this.deliveryInfo.phone = defaultAddress.receiverPhone || ''
					this.hasAddress = true
				} else {
					// 没有地址
					this.hasAddress = false
					this.deliveryInfo.id = ''
					this.deliveryInfo.address = ''
					this.deliveryInfo.name = ''
					this.deliveryInfo.phone = ''
				}
			}).catch(err => {
				console.error('获取地址失败:', err)
				this.hasAddress = false
			})
		},
		
		// 选择收货地址
		selectAddress() {
			uni.navigateTo({
				url: '/pages/inventoryManagement/addressManagement'
			})
		},
		
		// 选择收货日期
		selectDate() {
			// 直接显示日期选择器
			uni.showActionSheet({
				itemList: this.getDateOptions(),
				success: (res) => {
					// 获取实际日期并更新
					const today = new Date()
					const selectedDate = new Date(today)
					selectedDate.setDate(today.getDate() + res.tapIndex)
					this.deliveryDate = this.formatDate(selectedDate)
					
					uni.showToast({
						title: '日期已选择',
						icon: 'success'
					})
				}
			})
		},
		
		// 获取日期选项
		getDateOptions() {
			const options = []
			const today = new Date()
			
			// 生成未来7天的日期选项
			for (let i = 0; i < 30; i++) {
				const date = new Date(today)
				date.setDate(today.getDate() + i)
				const dateStr = this.formatDate(date)
				const displayStr = this.getDisplayDate(date, i)
				options.push(displayStr)
			}
			
			return options
		},
		
		// 获取显示格式的日期
		getDisplayDate(date, index) {
			const today = new Date()
			const tomorrow = new Date(today)
			tomorrow.setDate(today.getDate() + 1)
			
			if (index === 0) {
				return '今天 (' + this.formatDate(date) + ')'
			} else if (index === 1) {
				return '明天 (' + this.formatDate(date) + ')'
			} else {
				const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
				const weekday = weekdays[date.getDay()]
				return weekday + ' (' + this.formatDate(date) + ')'
			}
		},
		
		// 格式化日期
		formatDate(date) {
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			return `${year}-${month}-${day}`
		},
		
		// 选择支付方式
		selectPaymentMethod(index) {
			this.selectedPaymentIndex = index
			console.log('选择的支付方式:', this.paymentMethods[index])
		},
		
	submitOrder() {
		// // 验证必填信息
		// if (!this.deliveryInfo.address) {
		// 	uni.showToast({
		// 		title: '请选择收货地址',
		// 		icon: 'none'
		// 	})
		// 	return
		// }
		
		// if (!this.deliveryInfo.name) {
		// 	uni.showToast({
		// 		title: '收货人姓名不能为空',
		// 		icon: 'none'
		// 	})
		// 	return
		// }
		
		// if (!this.deliveryInfo.phone) {
		// 	uni.showToast({
		// 		title: '收货人手机号不能为空',
		// 		icon: 'none'
		// 	})
		// 	return
		// }
		
		// if (!this.deliveryDate) {
		// 	uni.showToast({
		// 		title: '请选择收货日期',
		// 		icon: 'none'
		// 	})
		// 	return
		// }
		
		if (!this.shopModel.officeCode) {
			uni.showToast({
				title: '请选择店铺名称',
				icon: 'none'
			})
			return
		}
		
		if (this.orderItems.length === 0) {
			uni.showToast({
				title: '购物车为空',
				icon: 'none'
			})
			return
		}
		
		// 获取选中的支付方式
		// const selectedPayment = this.paymentMethods[this.selectedPaymentIndex]
		
		// 如果选择的是线下转账，验证是否上传了转账记录
		// if (selectedPayment.value === '0' && !this.image.dataMap.order_transfer_image) {
		// 	uni.showToast({
		// 		title: '请上传转账记录',
		// 		icon: 'none'
		// 	})
		// 	return
		// }
		
		// 构建商品列表JSON格式
		const items = this.orderItems.map(item => ({
			productId: item.id,
			productName: item.name,
			price: item.price,
			costPrice: item.costPrice,
			quantity: item.quantity,
			image: item.image || ''
		}))
		
		// 构建请求参数对象
		const params = {}
		params.items = JSON.stringify(items)
		params.fromCart = this.fromCart
		// params.receiverName = this.deliveryInfo.name
		// params.receiverPhone = this.deliveryInfo.phone
		// params.receiverAddress = this.deliveryInfo.address
		// params.receiveDate = this.deliveryDate
		// params.payMethodId = selectedPayment.value
		// params.payMethod = selectedPayment.name
		params.remark = this.remarks || ''
		params.orderType = 2
		
		// 添加店铺信息
		if (this.shopModel.officeCode) {
			params.shopCode = this.shopModel.officeCode
			params.shopName = this.shopModel.officeName
		}
		
		// 添加图片相关参数
		// if (this.image.dataMap.order_transfer_image) {
		// 	params['dataMap[order_transfer_image]'] = this.image.dataMap.order_transfer_image
		// }
		// if (this.image.dataMap.order_transfer_image__del) {
		// 	params['dataMap[order_transfer_image__del]'] = this.image.dataMap.order_transfer_image__del
		// }
		
		// 如果有地址ID，也传递
		// if (this.deliveryInfo.id) {
		// 	params.addressId = this.deliveryInfo.id
		// }
		
		console.log('提交订单参数:', params)
		
		uni.showLoading({
			title: '提交中...',
			mask: true
		})
		
		// 调用创建订单接口
		this.$u.api.orderManagement.create(params).then(res => {
			uni.hideLoading()
			
			if (res && res.result === 'true') {
				uni.showToast({
					title: '订单提交成功',
					icon: 'success'
				})
				
				// 延迟跳转到订单列表
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/inventoryManagement/stockOrderList'
					})
				}, 1500)
			} else {
				uni.showToast({
					title: res.message || '订单提交失败',
					icon: 'none'
				})
			}
		}).catch(err => {
			uni.hideLoading()
			console.error('提交订单失败:', err)
			uni.showToast({
				title: '订单提交失败，请重试',
				icon: 'none'
			})
		})
	}
	},
}
</script>

<style scoped>
.container {
	background-color: #ffffff;
	padding-bottom: 80px;
}

/* 收货信息 */
.delivery-info {
	display: flex;
	align-items: center;
	padding: 20px;
	border-bottom: 1px solid #f0f0f0;
}

.address-icon {
	font-size: 20px;
	margin-right: 15px;
}

.address-content {
	flex: 1;
}

.address-text {
	font-size: 16px;
	color: #333333;
	font-weight: bold;
	margin-bottom: 5px;
	display: block;
}

.contact-info {
	font-size: 14px;
	color: #666666;
}

.no-address-text {
	font-size: 14px;
	color: #ff4069;
	font-weight: 500;
}

/* 自定义大于号箭头 */
.custom-arrow {
	position: relative;
	width: 8px;
	height: 12px;
	margin-left: 8px;
	transition: transform 0.2s ease;
}

.custom-arrow:active {
	transform: scale(0.95);
}

.custom-arrow::before {
	content: '';
	position: absolute;
	top: 6px;
	right: 0;
	width: 10px;
	height: 1.5px;
	background-color: #999999;
	transform: rotate(45deg);
	transform-origin: right center;
	border-radius: 1px;
}

.custom-arrow::after {
	content: '';
	position: absolute;
	bottom: 6px;
	right: 0;
	width: 10px;
	height: 1.5px;
	background-color: #999999;
	transform: rotate(-45deg);
	transform-origin: right center;
	border-radius: 1px;
}

/* 收货日期 */
.delivery-date {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20px;
	border-bottom: 1px solid #f0f0f0;
}

.date-label {
	font-size: 16px;
	color: #333333;
}

.date-content {
	display: flex;
	align-items: center;
}

.date-text {
	font-size: 16px;
	color: #333333;
	margin-right: 10px;
}

/* 支付方式 */
.payment-methods {
	padding: 20px;
	border-bottom: 1px solid #f0f0f0;
}

.payment-title {
	font-size: 16px;
	color: #333333;
	font-weight: bold;
	margin-bottom: 15px;
	display: block;
}

.payment-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 15px 0;
	border-bottom: 1px solid #f8f8f8;
}

.payment-item:last-child {
	border-bottom: none;
}

.payment-info {
	display: flex;
	align-items: center;
}

.payment-icon {
	font-size: 20px;
	margin-right: 15px;
}

.payment-name {
	font-size: 16px;
	color: #333333;
}

.payment-radio {
	width: 20px;
	height: 20px;
	border: 2px solid #ddd;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
}

.payment-radio.active {
	border-color: #ff4069;
}

.radio-dot {
	width: 10px;
	height: 10px;
	background-color: #ff4069;
	border-radius: 50%;
}

/* 转账记录上传 */
.transfer-record-upload {
	padding: 20px;
	border-bottom: 1px solid #f0f0f0;
}

.transfer-record-upload-title {
	font-size: 16px;
	color: #333333;
}
.transfer-record-upload-content {
	font-size: 16px;
	color: #333333;
}

/* 购买商品汇总 */
.purchase-summary {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20px;
	border-bottom: 1px solid #f0f0f0;
}

.summary-label {
	font-size: 16px;
	color: #333333;
}

.summary-text {
	font-size: 16px;
	color: #333333;
	font-weight: bold;
}

/* 店铺选择 */
.shop-section {
	padding: 20px;
	border-bottom: 1px solid #f0f0f0;
}

.shop-header {
	margin-bottom: 15px;
}

.shop-label {
	font-size: 16px;
	color: #333333;
}

/* 备注 */
.remarks-section {
	padding: 20px;
	border-bottom: 1px solid #f0f0f0;
}

.remarks-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 15px;
}

.remarks-label {
	font-size: 16px;
	color: #333333;
}

.remarks-limit {
	font-size: 14px;
	color: #ff4069;
}

.remarks-input {
	width: 90%;
	max-height: 70px;
	padding: 15px;
	border: 1px solid #f0f0f0;
	border-radius: 8px;
	font-size: 14px;
	color: #333333;
	background-color: #fafafa;
}

.store-name {
	font-size: 18px;
	color: #333333;
	font-weight: bold;
}

/* 商品列表 */
.order-items {
	padding: 20px;
}

.order-items-title {
	font-size: 16px;
	color: #333333;
	font-weight: bold;
	margin-bottom: 15px;
}

.order-item {
	display: flex;
	align-items: center;
	padding: 15px 0;
	border-bottom: 1px solid #f8f8f8;
}

.item-image {
	width: 60px;
	height: 60px;
	border-radius: 8px;
	margin-right: 15px;
	background-color: #f0f0f0;
}

.item-info {
	flex: 1;
}

.item-name {
	font-size: 12px;
	color: #333333;
	font-weight: bold;
	margin-bottom: 8px;
	display: block;
}

.item-details {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.item-costPrice {
	font-size: 10px;
	color: #666666;
	text-decoration: line-through;
	display: block;
}

.item-price {
	font-size: 12px;
	color: #333333;
	font-weight: bold;
}

.item-quantity {
	font-size: 12px;
	color: #666666;
}

/* 底部结算栏 */
.order-footer {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 60px;
	background-color: #ffffff;
	border-top: 1px solid #f0f0f0;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 20px;
	z-index: 100;
}

.total-info {
	display: flex;
	flex-direction: column;
	align-items: flex-start;
}

.price-item {
	display: flex;
	align-items: center;
	margin-bottom: 4px;
}

.price-item:last-child {
	margin-bottom: 0;
}

.total-label {
	font-size: 14px;
	color: #333333;
	margin-right: 5px;
}

.total-price {
	font-size: 16px;
	color: #ff4069;
	font-weight: bold;
}

.submit-btn {
	height: 40px;
	padding: 0 30px;
	background-color: #ff4069;
	border-radius: 20px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.submit-text {
	font-size: 16px;
	color: #ffffff;
	font-weight: bold;
}
</style>
